#include "mousetool.h"
#include "bmpeditor.h"

void MouseTool::updateCursor(const SPoint & a_mouse)
{
	BMPEditor* bmpe = (BMPEditor*)getContext();
	ZoomViewPanel * bv = bmpe->getZoomViewContent();
	SPoint pixelLoc = bv->pixelPointedAt(a_mouse);
	m_tool.setX(pixelLoc.getX()-m_tool.getWidth()/2);
	m_tool.setY(pixelLoc.getY()-m_tool.getHeight()/2);
	m_toolOnScreen.set(bv->getViewAreaOfPixel(m_tool.getMin()));
	m_toolOnScreen.w *= m_tool.w;
	m_toolOnScreen.h *= m_tool.h;
}

bool MouseTool::handleEvent(const SDL_Event & e)
{
	int wasUsingTool = m_usingTool;
	bool handled = false;
	bool mouseUpdated = false;
	SPoint mouse;
	switch(e.type)
	{
	case SDL_MOUSEBUTTONDOWN:
		mouseUpdated = true;
		mouse.set(e.button.x, e.button.y);
		m_usingTool = e.button.button;
		break;
	case SDL_MOUSEBUTTONUP:
		mouseUpdated = true;
		mouse.set(e.button.x, e.button.y);
		m_usingTool = 0;
		break;
	case SDL_MOUSEMOTION:
		mouseUpdated = true;
		mouse.set(e.motion.x,e.motion.y);
		break;
	}
	if(mouseUpdated)
	{
		// add the old mouse area to the dirty area, to replace the old position
		setDirty(0);
		// move the mouse area
		updateCursor(mouse);
	}
	if(wasUsingTool != m_usingTool)
	{
		handled |= releasedTool(wasUsingTool);
		if(m_usingTool)
		{
			handled |= pressedTool(m_usingTool);
		}
	}
	else if(m_usingTool)
	{
		handled |= draggedTool(m_usingTool);
	}
	if(mouseUpdated)
	{
		// add the new mouse area to the dirty area, to show the new position
		setDirty(0);
	}
	return handled;
}